package com.tom.zx.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tom.zx.entity.Contract;
import com.tom.zx.entity.FurnishOrder;
import com.tom.zx.entity.User;
import com.tom.zx.service.IContractService;
import com.tom.zx.service.IUserService;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.Arrays;

/**
 * 合同 前端控制器
 *
 * @author lp
 * @since 2022-04-09
 */
@RestController
@RequestMapping("/zx/contract")
@AllArgsConstructor
public class ContractController {

    private final IContractService contractService;

    private final IUserService userService;

    /**
     * 查询分页列表
     */
    @GetMapping("/page")
    public Page<Contract> loadPageContract(Page<Contract> page, Contract contract) {
        return contractService.page(page, new LambdaQueryWrapper<Contract>().like(Contract::getName, contract.getName()));
    }

    @GetMapping("/page/user")
    public Page<Contract> oadPageUserContract(Principal principal,Page<Contract> page, Contract contract) {
        final User user = userService.loadUserByUserName(principal.getName());

        return contractService.page(page, new LambdaQueryWrapper<Contract>()
                .like(Contract::getName, contract.getName())
                .eq(Contract::getSignatory,user.getId())
        );
    }
    /**
     * 保存合同信息
     */
    @PostMapping("user")
    public boolean saveContract(Principal principal, @RequestBody Contract contract) {
        final String userName = principal.getName();
        final User user = userService.loadUserByUserName(userName);
        contract.setSignatory(user.getId());
        contract.setStatus(0);//草稿状态
        return contractService.saveOrUpdate(contract);
    }

    @PostMapping
    public boolean saveContract2(@RequestBody Contract contract) {
        contract.setStatus(1);//草稿状态
        //创建订但
        return contractService.saveOrUpdate2(contract);
    }

    /**
     * 删除数据 通过ids
     */
    @DeleteMapping
    public boolean deleteContractByIds(@RequestBody Long[] ids) {
        return contractService.removeBatchByIds(Arrays.asList(ids));
    }

    /**
     * 更新状态
     */
    @PutMapping("/{contractId}/status")
    public boolean changeStatus(@PathVariable("contractId") Long contractId, Long status) {
        return contractService.update(new LambdaUpdateWrapper<Contract>().eq(Contract::getId, contractId).set(Contract::getStatus, status));
    }
}
